import redis, { RedisClientType } from 'redis'
import fs from 'fs'

let client: RedisClientType | undefined = undefined

function connect() {
  const filepath = './appsettings.json'
  const appsettings = JSON.parse(fs.readFileSync(filepath).toString())
  if (appsettings.host) {
    client = redis.createClient({ url: appsettings.host })
    client.connect()
    // const subscribe = client.duplicate()
    // subscribe.on('error', err => {
    //   console.error(err)
    // })
    // subscribe.connect()

    // const listener = (message, channel) => console.log(message, channel)
    // client.subscribe('event-name', listener)
  }
}

function getClient() {
  if (client?.isOpen) return client as RedisClientType
  connect()
  return client as RedisClientType
}

export default {
  connect,
  getClient
}
